package com.labofjet.system.controller;

import com.github.pagehelper.PageInfo;
import com.labofjet.common.dto.ContextDto;
import com.labofjet.system.dto.SysUserDto;
import com.labofjet.system.enums.EState;
import com.labofjet.system.service.impl.SysRoleServiceImpl;
import com.labofjet.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * User页面信息
 */
@RestController
public class SysUserController extends CrudBaseController {

	@Autowired
	private SysUserServiceImpl sysUserService;

	@Autowired
	private SysRoleServiceImpl sysRoleService;


	@RequestMapping("/user/list")
	public ContextDto list(@RequestBody ContextDto contextDto) {
		PageInfo<SysUserDto> sysUserDtos = sysUserService.list(contextDto);
		sysUserService.assembleRoleForUsers(sysUserDtos.getList());
		contextDto.setData(sysUserDtos);
		contextDto.setSuccess(true);

		return contextDto;
	}

	@RequestMapping("/user/load")
	public ContextDto load(@RequestBody ContextDto contextDto) {
		SysUserDto sysUserDto = sysUserService.load(contextDto);
		if (sysUserDto != null) {
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userId", sysUserDto.getId());
			m.put("state", EState.VALID.getCode());
			ContextDto context = new ContextDto();
			context.setRequestParams(m);
			sysUserDto.setSysRoleDtoList(sysRoleService.list(context).getList()); // 加载关联的role
		}
		contextDto.setData(sysUserDto);
		contextDto.setSuccess(true);

		return contextDto;
	}

	@RequestMapping("/user/save")
	public ContextDto save(@RequestBody ContextDto contextDto) {
		SysUserDto SysUserDtos = sysUserService.save(contextDto);
		contextDto.setData(SysUserDtos);
		contextDto.setSuccess(true);

		return contextDto;
	}

	@RequestMapping("/user/delete")
	public ContextDto delete(@RequestBody ContextDto contextDto) {
		int i = sysUserService.delete(contextDto);
		contextDto.setSuccess(true);
		contextDto.setMessage("成功删除了" + i + "条数据");
		return contextDto;
	}
}
